package com.polly.esphwevent.common.aspect;

/**
 *
 * @title:  SysLogAspect.java

 * @description:    TODO(用一句话描述该文件做什么)

 * @date:   2019年2月11日 下午3:03:16
 * @author ldz112@163.com
 * @version V1.0

 *
 */

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

//避免与原gaea冲突，设定优先级低的拦截
@Order(99)
@Aspect
@Component
@Slf4j
public class SysLogAspect {

    @Pointcut("execution(public * com.polly.esphwevent.controller.*.*(..))")
    public void pointCutMethod(){}

    //请求开始时间
    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Before("pointCutMethod()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        startTime.set(System.currentTimeMillis());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求的内容
        log.info("Aspect_Method:{},Aspect_URL:{},Aspect_Request:{}",request.getMethod(),request.getRequestURL().toString(),JSONObject.toJSONString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "ret" , pointcut = "pointCutMethod()")
    public void doAfterReturning(Object ret){
        //响应情况
        log.info("Aspect_Return:"+ JSONObject.toJSONString(ret) +",Aspect_executeTime:"+ (System.currentTimeMillis() - startTime.get()));
        startTime.remove();
    }

}
